window.addEventListener('load', function () {
    // 获取元素

    let tbody = this.document.querySelector('tbody')
    // 添加 --模态框
    let btnAdd = this.document.querySelector('.btnAdd')
    // 确认添加
    let btnaddsure = this.document.querySelector('.btnaddsure')
    // 省市级联
    // 用formData获取表单元素
    let form = this.document.querySelector('.add-form')
    // 省
    let province = this.document.querySelector('[name="province"]')
    // 市
    let city = this.document.querySelector('[name="city"]')
    // 县
    let county = this.document.querySelector('[name="county"]')

    // 添加和修改
    // 标题
    let addModalLabel = this.document.querySelector('#addModalLabel')
    // 姓名
    let nameEle = this.document.querySelector('[ name="name"]')
    // 年龄
    let ageEle = this.document.querySelector('[ name="age"]')
    // 组号
    let groupEle = this.document.querySelector('[ name="group"]')
    // 性别
    let sexEle = this.document.querySelectorAll('[ name="sex"]')
    // 手机
    let phoneEle = this.document.querySelector('[ name="phone"]')
    // 期望薪资
    let salaryEle = this.document.querySelector('[ name="salary"]')
    // 实际薪资
    let truesalaryEle = this.document.querySelector('[ name="truesalary"]')
    // 重置
    let btnreset = this.document.querySelector('.btnreset')

    // 渲染数据
    function init() {
        // 发出get请求
        axios({
            url: '/student/list'
        }).then(res => {
            // console.log(res)
            let data = res.data.data
            // console.log(data)

            // 数据渲染
            let htmlStr = ``
            data.forEach(function (value, index) {
                htmlStr += `  <tr>
            <th scope="row">${index + 1}</th>
            <td>${value.name}</td>
            <td>${value.age}</td>
            <td>${value.sex}</td>
            <td>${value.group}</td>
            <td>${value.phone}</td>
            <td>${value.salary}</td>
            <td>${value.truesalary}</td>
            <td>${value.province + value.city + value.county}</td>
            <td>
              <button type="button" data-id="${value.id}" class="btn btn-primary btn-sm btnxg">修改</button>
              <button type="button" data-id="${value.id}" class="btn btn-danger btn-sm btndel">删除</button>
            </td>
          </tr>`
            })
            tbody.innerHTML = htmlStr
        })

    }
    init()


    // 省市级联
    // 加载省的数据
    axios({
        url: '/geo/province'
    }).then(res => {
        // console.log(res)
        // 因为是数组，所以要遍历
        let htmlStr = `  <option selected value="">--省--</option>`
        res.data.forEach(function (value) {
            htmlStr += ` <option value="${value}">${value}</option>`
        })
        province.innerHTML = htmlStr
    })

    // 加载市的数据
    // 因为是下拉列表，所以用change
    let cityDone, countDone
    province.addEventListener('change', function () {
        let pname = province.value
        city.innerHTML = ` <option selected value="">--市--</option>`
        county.innerHTML = ` <option selected value="">--县--</option>`
        // 判断如果没有选择省，则不会出现市的下拉列表选项
        if (!pname) {
            return
        }

        // 发起get请求
        axios({
            url: '/geo/city',
            params: { pname }
        }).then(res => {
            // console.log(res)
            let htmlStr = ` <option selected value="">--市--</option>`
            res.data.forEach(function (value) {
                htmlStr += `<option value="${value}">${value}</option>`
            })
            city.innerHTML = htmlStr
            // 说明市下拉列表选项加载完毕了
            cityDone = true
        })
    })

    // 加载市的县的数据

    city.addEventListener('change', function () {
        let pname = province.value
        let cname = city.value

        axios({
            url: '/geo/county',
            params: { pname, cname }
        }).then(res => {
            // console.log(res)
            let htmlStr = ` <option selected value="">--县--</option>`
            res.data.forEach(function (value) {
                htmlStr += `<option value="${value}">${value}</option>`
            })
            county.innerHTML = htmlStr
             // 说明市下拉列表选项加载完毕了
             countDone = true
        })
    })

    // 弹出--添加学员信息的模态框
    btnAdd.addEventListener('click', function () {
        // 重置表单元素
        btnreset.click()
        $('#addModal').modal('show')

        addModalLabel.innerHTML = '添加学员信息'
        btnaddsure.innerHTML = '确认添加'


    })

    // 表单验证
    function student() {
        return {
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空',
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度2~10位'
                        }
                    }
                },
                age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空',
                        },
                        greaterThan: {
                            value: 18,
                            message: '年龄不能小于18岁'
                        },
                        lessThan: {
                            value: 60,
                            message: '年龄不能超过60岁'
                        }
                    }
                },
                sex: {
                    validators: {
                        choice: {
                            min: 1,
                            max: 1,
                            message: '请选择性别'
                        }
                    }
                },
                group: {
                    validators: {
                        notEmpty: {
                            message: '组号不能为空',
                        },
                        regexp: {
                            regexp: /^\d{1,2}$/,
                            message: '请选择有效的组号'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空',
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请填写有效的手机号'
                        }
                    }
                },
                salary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '期望薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '期望薪资不能高于100000'
                        }
                    }
                },
                truesalary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '实际薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '实际薪资不能高于100000'
                        }
                    }
                },
                province: {
                    validators: {
                        notEmpty: {
                            message: '省份必填',
                        },
                    }
                },
                city: {
                    validators: {
                        notEmpty: {
                            message: '市必填',
                        },
                    }
                },
                county: {
                    validators: {
                        notEmpty: {
                            message: '县必填',
                        },
                    }
                },
            }
        }
    }

    // 添加用户
    // 因为上面用了表单验证
    // btnaddsure.addEventListener('click', function (e) 
    let eitid
    $('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
        // 阻止默认行为
        e.preventDefault()
        // 通过formdata收集表单数据
        let formdata = new FormData(form)
        let data = {}
        // 借助forEach将formdata转换为对象
        formdata.forEach(function (value, key) {
            // console.log(value, key)
            data[key] = value
        })

        // 后台能否传递数据
        // 修改和添加共用一个模态框
        if (addModalLabel.innerHTML === '添加学员信息') {
            axios({
                url: '/student/add',
                method: 'post',
                data
            }).then(res => {
                console.log(res)
                if (res.data.code == 0) {
                    // 弹出提示框
                    toastr.success(res.data.message)
                    // 关闭模态框
                    $('#addModal').modal('hide')
                    init()

                }
            })
        } else {
            // 因为修改需要id值
            data.id = eitid
            axios({
                url: '/student/update',
                method: 'put',
                data
            }).then(res => {
                console.log(res)
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    // 关闭模态框
                    $('#addModal').modal('hide')
                    init()
                    eitid = undefined
                }
            })
        }



    })


    // 删除学员
    tbody.addEventListener('click', function (e) {
        // 事件委托 
        if (e.target.classList.contains('btndel')) {
            // console.log(123)
            if (confirm('确定要删除改学员信息吗？')) {
                let id = e.target.dataset.id
                // console.log(id)
                // 发起DELETE请求
                axios({
                    url: '/student/delete',
                    method: 'delete',
                    params: { id }

                }).then(res => {
                    // console.log(res)
                    if (res.data.code == 0) {
                        toastr.success(res.data.message)
                        init()
                    }
                })
            }

        }



    })

    // 编辑,修改　修改和添加共用一个模态框
    // 数据回填
    // 
    tbody.addEventListener('click', function (e) {
        if (e.target.classList.contains('btnxg')) {
            // console.log(123)
            let id = e.target.dataset.id
            eitid = id
            // console.log(id)
            // 弹出模态框=>修改和添加的模态框共用
            $('#addModal').modal('show')
            addModalLabel.innerHTML = '修改学员信息'
            btnaddsure.innerHTML = '确认修改'

            axios({
                url: "/student/one",
                params: { id }
            }).then(res => {
                // console.log(res)
                let data = res.data.data
                // console.log(data)
                // 回填数据
                nameEle.value = data.name
                ageEle.value = data.age
                groupEle.value = data.group
                // 性别
                // sexEle.value=data.sex
                // 单选按钮。用checked属性判断
                data.sex === '男' ? (sexEle[0].checked = true) : (sexEle[1].checked = true)
                phoneEle.value = data.phone
                salaryEle.value = data.salary
                truesalaryEle.value = data.truesalary

                province.value = data.province
                // 下拉列表回填
                let ev = document.createEvent('HtmlEvents')
                ev.initEvent('change', true, true)
                province.dispatchEvent(ev)
                // 轮询
                let tid = setInterval(function () {
                    if (cityDone) {
                        clearInterval(tid)
                        city.value = data.city
                        let ev1 = document.createEvent('HtmlEvents')
                        ev1.initEvent('change', true, true)
                        city.dispatchEvent(ev1)
                        tid = setInterval(function () {
                            if (countDone) {
                                county.value = data.county
                            }
                        }, 100)
                    }
                }, 100)

            })
        }
    })

})